package com.lagou.web.servlet;

import com.lagou.utils.UUIDUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload")
public class UploadFile extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("utf-8");
            boolean multipartContent = upload.isMultipartContent(req);
            if (multipartContent) {
                List<FileItem> list = upload.parseRequest(req);

                if(list!=null){
                    for (FileItem item:list){
                        boolean formField = item.isFormField();
                        if(formField){
                            String fieldName = item.getFieldName();
                            String value = item.getString("utf-8");
                            System.out.println(fieldName+"="+value);


                        }else {
                            String name = item.getName();
                            String newName = UUIDUtils.getUUID()+"_"+name;
                            InputStream in = item.getInputStream();

                            String realPath = this.getServletContext().getRealPath("/");
                            System.out.println(realPath);

                            String path = realPath.substring(0, realPath.indexOf("unit_Web"));




                            FileOutputStream out = new FileOutputStream(path+"/public/"+newName);

                            IOUtils.copy(in,out);

                            in.close();
                            out.close();


                        }

                    }
                }

            }

        }catch(FileUploadException e){
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
